﻿//==================================================================
// Copyright (C) 2015 福流网络
// 作 者：江怀玉
// 日 期：2015-4-23
// 描 述：实现一些常用的全局功能(参照CS)
// 版 本：1.00
// 修改历史纪录
// 版 本  修改时间      修改人            修改内容
//==================================================================
using System;
using System.Collections.Generic;
using System.Web;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Text;
using System.Reflection;
using System.IO;
using System.Web.Script.Serialization;
using System.Collections;
using System.Data;



namespace FL.Common
{

    /// <summary>
    /// 用途：用于全局使用
    /// 
    /// </summary>
    public class Globals
    {

        // the HTML newline character
        public const String HtmlNewLine = "<br />";
        public const String _appSettingsPrefix = "AspNetForumsSettings.";
        public static Regex _pathComponentTextToEscape = new Regex(@"([^A-Za-z0-9\- ]+|\.| )", RegexOptions.Singleline | RegexOptions.Compiled);
        public static Regex _pathComponentTextToUnescape = new Regex(@"((?:_(?:[0-9a-f][0-9a-f][0-9a-f][0-9a-f])+_)|\+)", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
        public static Regex _fileComponentTextToEscape = new Regex(@"([^A-Za-z0-9 ]+|\.| )", RegexOptions.Singleline | RegexOptions.Compiled);
        public static Regex _fileComponentTextToUnescape = new Regex(@"((?:_(?:[0-9a-f][0-9a-f][0-9a-f][0-9a-f])+_)|_|\-)", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);

        //public const String Blank_Guid = Guid.Empty.ToByteAr;

        public static void RedirectToSSL(HttpContext context)
        {
            if (!context.Request.IsSecureConnection)
            {
                Uri url = context.Request.Url;
                context.Response.Redirect("https://" + url.ToString().Substring(7));
                // context.Response.End();
            }
        }
        /// <summary>
        /// 将httpRequestBase的Form转换成Hashstable 2015-09-22
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static Hashtable GetHashtableByRequest(HttpRequestBase request)
        {
            Hashtable ht = new Hashtable();

            foreach (string key in request.Form.AllKeys)
            {
                ht.Add(key, request.Form[key]);
            }
            return ht;
        }

        public static Guid CreatBlankGuid()
        {
            return  Guid.Empty;
        }

        public static string Home()
        {
            return "/";
        }


        #region FormatSignature
        public static string FormatSignature(string userSignature)
        {
            if (userSignature != null && userSignature.Length > 0)
                return "<hr size=\"1\" align=\"left\" width=\"25%\">" + userSignature.Replace("\r\n", "<br>");
            else
                return String.Empty;
        }
        #endregion


        #region Encode/Decode

        /// <summary>
        /// Converts a prepared subject line back into a raw text subject line.
        /// </summary>
        /// <param name="textToFormat">The prepared subject line.</param>
        /// <returns>A raw text subject line.</returns>
        /// <remarks>This function is only needed when editing an existing message or when replying to
        /// a message - it turns the HTML escaped characters back into their pre-escaped status.</remarks>
        public static string HtmlEncode(String textToFormat)
        {
            // strip the HTML - i.e., turn < into &lt;, > into &gt;

            if (IsNullorEmpty(textToFormat))
                return textToFormat;

            //ScottW: Removed Context dependency
            return System.Web.HttpUtility.HtmlEncode(textToFormat);
            //return HttpContext.Current.Server.HtmlEncode(FormattedMessageSubject);
        }

        public static string UrlEncode(string urlToEncode)
        {
            if (IsNullorEmpty(urlToEncode))
                return urlToEncode;

            return System.Web.HttpUtility.UrlEncode(urlToEncode).Replace("'", "%27");
        }


        public static string UrlDecode(string urlToDecode)
        {
            if (IsNullorEmpty(urlToDecode))
                return urlToDecode;

            return System.Web.HttpUtility.UrlDecode(urlToDecode.Replace("\\\\", "\\"));
        }

        public static string UrlEncodePathComponent(string text)
        {
            return UrlEncode(text, _pathComponentTextToEscape, '+', '_');
        }

        public static string UrlDecodePathComponent(string text)
        {
            return UrlDecode(text, _pathComponentTextToUnescape);
        }


        public static string UrlEncodeFileComponent(string text)
        {
            return UrlEncode(text, _fileComponentTextToEscape, '-', '_');
        }

        public static string UrlDecodeFileComponent(string text)
        {
            return UrlDecode(text, _fileComponentTextToUnescape);
        }

        private static string UrlEncode(string text, Regex pattern, char spaceReplacement, char escapePrefix)
        {
            if (IsNullorEmpty(text))
                return text;

            Match match = pattern.Match(text);
            StringBuilder encText = new StringBuilder();
            int lastEndIndex = 0;
            while (match.Value != string.Empty)
            {
                if (lastEndIndex != match.Index)
                    encText.Append(text.Substring(lastEndIndex, match.Index - lastEndIndex));

                if (match.Value == " ")
                    encText.Append(spaceReplacement);
                else if (match.Value == "." && match.Index != text.Length - 1)
                    encText.Append("."); // . at the end of text causes a 404... only encode . at the end of text
                else
                {
                    encText.Append(escapePrefix);
                    byte[] bytes = Encoding.Unicode.GetBytes(match.Value);
                    if (bytes != null)
                    {
                        foreach (byte b in bytes)
                        {
                            string hexByte = b.ToString("X");

                            if (hexByte.Length == 1)
                                encText.Append("0");

                            encText.Append(hexByte);
                        }
                    }
                    encText.Append(escapePrefix);
                }

                lastEndIndex = match.Index + match.Length;
                match = pattern.Match(text, lastEndIndex);
            }

            if (lastEndIndex < text.Length)
                encText.Append(text.Substring(lastEndIndex));

            return encText.ToString();
        }

        private static string UrlDecode(string text, Regex pattern)
        {
            if (IsNullorEmpty(text))
                return text;

            Match match = pattern.Match(text);
            StringBuilder decText = new StringBuilder();
            int lastEndIndex = 0;
            while (match.Value != string.Empty)
            {
                if (lastEndIndex != match.Index)
                    decText.Append(text.Substring(lastEndIndex, match.Index - lastEndIndex));

                if (match.Value.Length == 1)
                    decText.Append(" ");
                else
                {
                    byte[] bytes = new byte[(match.Value.Length - 2) / 2];

                    for (int i = 1; i < match.Value.Length - 1; i += 2)
                        bytes[(i - 1) / 2] = byte.Parse(match.Value.Substring(i, 2), NumberStyles.AllowHexSpecifier);

                    decText.Append(Encoding.Unicode.GetString(bytes));
                }

                lastEndIndex = match.Index + match.Length;
                match = pattern.Match(text, lastEndIndex);
            }

            if (lastEndIndex < text.Length)
                decText.Append(text.Substring(lastEndIndex));

            return decText.ToString();
        }

        #endregion

        public static int SafeInt(string text, int defaultValue)
        {
            if (!IsNullorEmpty(text))
            {
                try
                {
                    return Int32.Parse(text);
                }
                catch (Exception) { }

            }
            return defaultValue;
        }


        public static bool SafeBool(string text, bool defaultValue)
        {
            if (!IsNullorEmpty(text))
            {
                try
                {
                    return bool.Parse(text);
                }
                catch (Exception) { }

            }

            return defaultValue;
        }


        public static bool IsNullorEmpty(string text)
        {
            return text == null || text.Trim() == string.Empty;
        }

        /// <summary>
        /// 是否日期格式
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static bool IsDate(string text)
        {
            if (IsNullorEmpty(text))
                return false;

            try
            {
                DateTime dt = DateTime.Parse(text);
                return true;
            }
            catch (Exception) { }

            return false;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        public static string HostPath(Uri uri)
        {
            string portInfo = uri.Port == 80 ? string.Empty : ":" + uri.Port.ToString();
            return string.Format("{0}://{1}{2}", uri.Scheme, uri.Host, portInfo);
        }

        /// <summary>
        /// 全地址
        /// </summary>
        /// <param name="local"></param>
        /// <returns></returns>
        public static string FullPath(string local)
        {
            if (IsNullorEmpty(local))
                return local;

            if (local.ToLower().StartsWith("http://") || local.ToLower().StartsWith("https://"))
                return local;

            if (HttpContext.Current == null)
                return local;

            return FullPath(HostPath(HttpContext.Current.Request.Url), local);
        }

        public static string FullPath(string hostPath, string local)
        {
            return hostPath + local;
        }

        /// <summary>
        /// Adds a string to the current url determining the correct seperator character
        /// </summary>
        /// <param name="url"></param>
        /// <param name="querystring"></param>
        /// <returns></returns>
        public static string AppendQuerystring(string url, string querystring)
        {
            return AppendQuerystring(url, querystring, false);
        }

        public static string AppendQuerystring(string url, string querystring, bool urlEncoded)
        {
            string seperator = "?";
            if (url.IndexOf('?') > -1)
            {
                if (!urlEncoded)
                    seperator = "&";
                else
                    seperator = "&amp;";
            }
            return string.Concat(url, seperator, querystring);
        }

        public static void Return404(HttpContext Context)
        {
            Context.Response.StatusCode = 404;
            Context.Response.SuppressContent = true;
            Context.Response.End();
        }


        public static string JoinIntArray(string separator, int[] intArray)
        {
            if (intArray != null && intArray.Length > 0)
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i <= intArray.GetUpperBound(0); i++)
                {
                    if (i != 0)
                        sb.Append(separator);
                    sb.Append(intArray[i]);
                }
                return sb.ToString();
            }
            else
            {
                return string.Empty;
            }
        }


        public static int ConvertInt(object o)
        {
            try
            {
                return o == null ? 0 : (int)o;
            }
            catch
            {
                return 0;
            }
        }

        public static string ConverString(object o)
        {
            try
            {
                return o == null ? "" : o as string;
            }
            catch
            {
                return "";
            }
        }

        public static string ConverDateTime(object o)
        {
            try
            {
                return o == null ? "1900-01-01" : ((DateTime)o).ToString("yyyy-MM-dd");
            }
            catch
            {
                return "";
            }
        }


        /// <summary>
        /// 查看文件类型，是不是在所列出的文件类型中
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <param name="Extype">文件后缀类型</param>
        /// <returns>ture or false</returns>
        public static bool IIFExistExtension(string filename, string[] Extype)
        {
            string _ext = Path.GetExtension(filename).ToLower();
            foreach (string ext in Extype)
            {
                if (_ext == "." + ext.ToLower())
                    return true;
            }
            return false;
        }


        /// <summary>
        /// 获取文件后缀名
        /// </summary>
        /// <param name="?">获取文件名</param>
        /// <returns>当前文件的后缀名</returns>
        public static string GetExtensions(string filename)
        {
            return Path.GetExtension(filename).ToLower();
        }
        /// <summary>
        /// 获取文件后缀　
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns></returns>
        public static string GetExtension(string filename)
        {
            if (filename.IndexOf('.') > 0)
            {
                return System.IO.Path.GetExtension(filename).Remove(0, 1).ToLower();
            }
            return "";
        }

        /// <summary>
        /// 获取客户端IP
        /// </summary>
        /// <returns></returns>
        public static string GetClientIp()
        {
            return HttpContext.Current.Request.UserHostAddress;
        }

        /// <summary>
        /// 获取当前目录
        /// </summary>
        /// <returns></returns>
        public static string GetDir()
        {
            return HttpContext.Current.Request.PhysicalApplicationPath;
        }


        /// <summary>
        /// 获取用户设置头象
        /// </summary>
        /// <param name="username">用户</param>
        /// <returns>头像目录</returns>
        public static string GetAvater(string username)
        {
            string[] _ext = { "gif", "jpg", "png" };
            foreach (string ext in _ext)
            {
                if (System.IO.File.Exists(string.Format(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "/images/header/{0}.{1}", username, ext)))
                {
                    return string.Format("/images/header/{0}.{1}", username, ext);
                }
            }
            return "";
        }

        /// <summary>
        /// 获取当前地址
        /// </summary>
        /// <returns>当前地址</returns>
        public static string GetCurrentUrl()
        {
            return HttpContext.Current.Request.Url.AbsoluteUri;
        }


        /// <summary>
        /// 页页转接
        /// </summary>
        /// <param name="url"></param>
        public static void LeaveSecureConnection(string url)
        {
            if (System.Web.HttpContext.Current.Request.IsSecureConnection)
            {
                url = string.Format("http://{0}{1}", HttpContext.Current.Request.Url.Host, url);
            }
            System.Web.HttpContext.Current.Response.Redirect(url, true);
        }


        /// <summary>
        /// 创建目录
        /// </summary>
        /// <param name="path">路径</param>
        public static void CreateDir(string path)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }


        /// <summary>
        /// 获取用户头像,如果没有设置的话，就返回默认图片
        /// </summary>
        /// <param name="username">用户</param>
        /// <returns></returns>
        public static string getPic(string username)
        {
            if (username != "")
            {
                string[] ext = { "gif", "jpg", "png" };
                foreach (string _ext in ext)
                {
                    if (System.IO.File.Exists(string.Format(Globals.GetDir() + "/uploadfile/pic/{0}.{1}", username, _ext)))
                        return string.Format("/uploadfile/pic/{0}.{1}", username, _ext);
                }
            }
            return "/uploadfile/pic/no_photo.gif";
        }




        /// <summary>
        /// 将实体对象转化成JSON格式,一般只对实现类进行操作。
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static string getJSON(object o)
        {
            if (o is FL.DBModule.BaseEntity)
            {
                StringBuilder _json = new StringBuilder(string.Empty);
                string _name = o.GetType().Name;
                string _strjson = "{";
                //string _strjson = "{\"" + _name + "\":[{";
                _json.Append(_strjson);
                //　利用反射获类的属性名称和属性值　
                Type t = o.GetType();
                PropertyInfo[] Mypropertyinfos = t.GetProperties();
                foreach (PropertyInfo pi in Mypropertyinfos)
                {
                    try
                    {
                        if (pi.Name == "BaseEntityState" || pi.Name == "IsGuid")
                        {
                            continue;
                        }

                        {
                            Object Value = t.InvokeMember(pi.Name,
                                BindingFlags.DeclaredOnly |
                                BindingFlags.Public | BindingFlags.NonPublic |
                                BindingFlags.Instance | BindingFlags.GetProperty, null, o, null);
                            _json.Append(string.Format("\"{0}\":\"{1}\",", pi.Name, ObjectToString(Value).Replace("\\","\\").Replace("\"", "\\\"").Replace("\n", "\\n").Replace("\r", "\\r".Replace("'", "'"))));

                            //_json.Append(string.Format("\"{0}\":\"{1}\",", pi.Name, ObjectToString(Value).Replace("\n", "\\\\n").Replace("\r", "\\\\r".Replace("'", "'").Replace("\"", "\\\""))));
                        }
                    }
                    catch (System.Exception e)
                    {
                        //throw e;
                    }
                }

                return _json.ToString().Remove(_json.ToString().Length - 1) + "}";
            }
            else
            {
                JavaScriptSerializer s = new JavaScriptSerializer();
                return s.Serialize(o);
            }
            //return _json.ToString().Remove(_json.ToString().Length - 1) + "]}";
        }


        
        /// <summary>
        /// 将Json转换成Dic，用于记录Key/Value
        /// </summary>
        /// <param name="Json"></param>
        /// <returns></returns>
        public static Dictionary<string, object> ConvertJsonToDictionary(string Json)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            if (Json.Length < 5)
            {
                return dic;
                //return new Hashtable();
            }
            string strJson = Json;
            strJson = strJson.Remove(0, 2);
            strJson = strJson.Remove(strJson.Length - 2, 2);
            strJson = strJson.Replace("\", \"", "\",\""); // 该行是用于IE6,IE7的Json字符串处理
            string[] s = { "\",\"" };
            string[] s1 = { "\":\"" };
            string[] strArray = strJson.Split(s, StringSplitOptions.None);
            foreach (string str in strArray)
            {
                string[] _strArray = str.Split(s1, StringSplitOptions.None);
                if (_strArray.Length > 1)
                {
                    if (_strArray[0].IndexOf('"') == 1)
                    {
                        dic.Add(_strArray[0].Remove(0, 1), UrlDecode(_strArray[1]));
                    }
                    else
                    {
                        dic.Add(_strArray[0], UrlDecode(_strArray[1]));
                    }
                }
            }
            return dic;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Json"></param>
        /// <returns></returns>
        public static Dictionary<string, object> ConvertToDictionary(string Json)
        {
            JavaScriptSerializer s = new JavaScriptSerializer();
            Dictionary<string, object> JsonData = (Dictionary<string, object>)s.DeserializeObject(Json);
            return JsonData;
        }

        public static object CovertValue(string DFieldType,string strValue)
        {
            if (strValue == null)
            {
                return null;
            }
            switch (DFieldType.ToLower())
            {
                case "uniqueidentifier":
                    Guid guid = Guid.NewGuid();
                    try
                    {
                        guid = Guid.Parse(strValue);
                    }
                    catch { }
                    return guid;
                    //return typeof(Guid);
                case "varchar":
                    return strValue;
                case "nvarchar":
                    return strValue;
                    //return typeof(string);
                case "datetime":
                    DateTime dt = new DateTime();
                    try
                    {
                        dt = DateTime.Parse(strValue);
                    }
                    catch { };
                    return dt;
                case "int":
                    int i = 0;
                    try
                    {
                        i = int.Parse(strValue);
                    }
                    catch
                    {
                    }
                    return i;
                case "money":
                    Double d = 0.0;
                    try
                    {
                       d = Double.Parse(strValue);
                    }
                    catch
                    {
                    }
                    return d;
                case "nchar":
                    return strValue;
                case "ntext":
                    return strValue;
                case "smalldatetime":
                      DateTime sdt = new DateTime();
                    try
                    {
                        sdt = DateTime.Parse(strValue);
                    }
                    catch { };
                    return sdt;
                case "bigint": 
                    long l = 0;
                    try
                    {
                        l = long.Parse(strValue);
                    }
                    catch
                    {
                    }
                    return l;
                //case "binary":
                //    return typeof(Byte[]);
                case "bit":
                    bool  bl= true;
                    try
                    {
                        bl = bool.Parse(strValue);
                    }
                    catch
                    {

                    }
                    return bl;
                case "float": 
                    Double d1 = 0.0;
                    try
                    {
                        d1 = Double.Parse(strValue);
                    }
                    catch
                    {
                    }
                    return d1;
                    
                //case "image":
                //    return typeof(Byte[]);
                case "numeric":
                    System.Decimal n = 0;
                    try
                    {
                        n = Decimal.Parse(strValue);
                    }
                    catch
                    {
                    }
                    return n;
                case "real":
                    return bool.Parse(strValue);
                default:
                    return typeof(string);
            }
        }

        public static  Type CovertDBType(string DFieldType)
        {
            switch (DFieldType.ToLower())
            {
                case "uniqueidentifier":
                    return typeof(Guid);
                case "varchar":
                    return typeof(string);
                case "nvarchar":
                    return typeof(string);
                case "datetime":
                    return typeof(DateTime);
                case "int":
                    return typeof(int);
                case "money":
                    return typeof(Double);
                case "nchar":
                    return typeof(string);
                case "ntext":
                    return typeof(string);
                case "smalldatetime":
                    return typeof(DateTime);
                case "bigint":
                    return typeof(long);
                case "binary":
                    return typeof(Byte[]);
                case "bit":
                    return typeof(Boolean);
                case "float":
                    return typeof(Double);
                case "image":
                    return typeof(Byte[]);
                case "numeric":
                    return typeof(Decimal);
                case "real":
                    return typeof(Boolean);
                default:
                    return typeof(string);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string getJSON<T>(IList<T> list)
        {
            StringBuilder sb = new StringBuilder("");
            int i = 0;
            foreach (T t in list)
            {
                i = i + 1;
                string str = (i == list.Count) ? "" : ",";
                sb.Append(getJSON(t) + str);
            }
            return sb.ToString();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="strEntity"></param>
        /// <returns></returns>
        public static object getEntity(string strEntity)
        {
            object entity = FL.Common.Reflection.CreateEntitysInstance(strEntity);
            return entity;
        }
        /// <summary>
        /// 将实体对象转化成JSON数据格式
        /// </summary>
        /// <param name="o">实体对象</param>
        /// <returns>JSON数据格式</returns>
        public static string ObjectToJSON(object o)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            return jss.Serialize(o);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dr"></param>
        /// <param name="TableCols"></param>
        /// <returns></returns>
        public static string DataRowToJSON(System.Data.DataRow dr,HashSet<String> TableCols)
        {
            StringBuilder SJson = new StringBuilder("");
            foreach (string colName in TableCols)
            {
                object o = dr[colName];

                string v = ObjectToString(o);
                string str = "\""+colName+"\":\"" + (v==null?"":v.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", "\\n").Replace("\r", "\\r").Replace("'", "'")) +"\","; /*v.Replace("\r","\\r").Replace("\\","\\\\").Replace("\"","\\\"").Replace("\n","\\n")) +"\",";*/
                SJson.Append(str);
            }
            return "{" + SJson.ToString().Remove(SJson.Length - 1, 1)+"}";
        }
        /// <summary>
        /// 数据行转换成JSON
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        public static string DataRowToJSON(System.Data.DataRow dr)
        {
            HashSet<String> cols = GetDTCols(dr.Table);
            return  DataRowToJSON(dr,cols);
        }
        /// <summary>
        /// 数据表转换成JSON
        /// </summary>
        /// <param name="DT"></param>
        /// <returns></returns>
        public static string DataTableToJSON(System.Data.DataTable DT)
        {
            if (DT == null)
            {
                return "";
            }
            if (DT.Rows.Count == 0)
            {
                return "";
            }
            StringBuilder SJson = new StringBuilder("");
            foreach(System.Data.DataRow  dr in DT.Rows)
            {
                SJson.Append(DataRowToJSON(dr)+",");
            }
            return "["+SJson.ToString().Remove(SJson.Length-1,1)+"]";
        }
        public static ArrayList ToArrayList(DataTable data)
        {
            ArrayList array = new ArrayList();
            for (int i = 0; i < data.Rows.Count; i++)
            {
                DataRow row = data.Rows[i];

                Hashtable record = new Hashtable();
                for (int j = 0; j < data.Columns.Count; j++)
                {
                    object cellValue = row[j];
                    if (cellValue.GetType() == typeof(DBNull))
                    {
                        cellValue = null;
                    }
                    record[data.Columns[j].ColumnName] = cellValue;
                }
                array.Add(record);
            }
            return array;
        }

        /// <summary>
        /// 将datatable转换为json  
        /// </summary>
        /// <param name="dtb">Dt</param>
        /// <returns>JSON字符串</returns>
        public static string DataTableToCJson(System.Data.DataTable dtb)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            System.Collections.ArrayList dic = new System.Collections.ArrayList();
            foreach (System.Data.DataRow dr in dtb.Rows)
            {
                System.Collections.Generic.Dictionary<string, object> drow = new System.Collections.Generic.Dictionary<string, object>();
                foreach (System.Data.DataColumn dc in dtb.Columns)
                {
                    drow.Add(dc.ColumnName, dr[dc.ColumnName]);
                }
                dic.Add(drow);

            }
            //序列化  
            return jss.Serialize(dic);
        }


        /// <summary>    
        /// 将获取的Json数据转换为DataTable    
        /// </summary>    
        /// <param name="strJson">Json字符串</param>   
       /// <returns></returns>    
        public static System.Data.DataTable JsonToDataTable(string strJson)
        {
            //取出表名           
            var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase);
            string strName = rg.Match(strJson).Value;
            System.Data.DataTable tb = null;
            //去除表名            strJson = strJson.Substring(strJson.IndexOf("[") + 1);       
            strJson = strJson.Substring(0, strJson.IndexOf("]"));
            //获取数据            rg = new Regex(@"(?<={)[^}]+(?=})");         
            MatchCollection mc = rg.Matches(strJson);
            for (int i = 0; i < mc.Count; i++)
            {
                string strRow = mc[i].Value;
                string[] strRows = strRow.Split(',');

                //创建表        
                if (tb == null)
                {
                    tb = new System.Data.DataTable();
                    tb.TableName = strName;
                    foreach (string str in strRows)
                    {
                        var dc = new System.Data.DataColumn();
                        string[] strCell = str.Split(':');
                        dc.ColumnName = strCell[0];
                        tb.Columns.Add(dc);
                    }
                    tb.AcceptChanges();
                }
                //增加内容    
                System.Data.DataRow dr = tb.NewRow();
                for (int r = 0; r < strRows.Length; r++)
                {
                    dr[r] = strRows[r].Split(':')[1].Trim().Replace("，", ",").Replace("：", ":").Replace("\"", "");
                } tb.Rows.Add(dr);
                tb.AcceptChanges();
            }
            return tb;
        }

       

        /// <summary>
        /// List转成json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string ListToJson<T>(IList<T> list)
        {
            System.Text.StringBuilder Json = new System.Text.StringBuilder();

            Json.Append("[");
            if (list.Count > 0)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    T obj = Activator.CreateInstance<T>();
                    System.Reflection.PropertyInfo[] pi = obj.GetType().GetProperties();
                    Json.Append("{");
                    for (int j = 0; j < pi.Length; j++)
                    {
                        if (pi[j].GetValue(list[i], null) != null)
                        {
                            Type type = pi[j].GetValue(list[i], null).GetType();
                            Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));

                            if (j < pi.Length - 1)
                            {
                                Json.Append(",");
                            }
                        }
                    }
                    Json.Append("}");
                    if (i < list.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]");
            return Json.ToString();
        }
        /// <summary>
        /// List转成json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonName"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string ListToJson<T>(IList<T> list, string jsonName)
        {
            System.Text.StringBuilder Json = new System.Text.StringBuilder();
            if (string.IsNullOrEmpty(jsonName))
                jsonName = list[0].GetType().Name;
            Json.Append("{\"" + jsonName + "\":[");
            if (list.Count > 0)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    T obj = Activator.CreateInstance<T>();
                    System.Reflection.PropertyInfo[] pi = obj.GetType().GetProperties();
                    Json.Append("{");
                    for (int j = 0; j < pi.Length; j++)
                    {
                        if (pi[j].GetValue(list[i], null) != null)
                        {
                            Type type = pi[j].GetValue(list[i], null).GetType();
                            Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));

                            if (j < pi.Length - 1)
                            {
                                Json.Append(",");
                            }
                        }
                    }
                    Json.Append("}");
                    if (i < list.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]}");
            return Json.ToString();
        }
        /// <summary>
        /// 格式化字符型、日期型、布尔型
        /// </summary>
        /// <param name="str"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private static string StringFormat(string str, Type type)
        {
            if (type != typeof(string))
            {
                str = "\"" + str + "\"";
            }
            else if (string.IsNullOrEmpty(str))
            {
                str = "\"" + str + "\"";
            }
            else if (type == typeof(string))
            {
                str = String2Json(str);
                str = "\"" + str + "\"";
            }
            else if (type == typeof(DateTime))
            {
                str = "\"" + str.Split(' ')[0] + "\"";
            }
            else if (type == typeof(bool))
            {
                str = "\"" + str.ToLower() + "\"";
            }
            else if (type == typeof(Guid))
            {
                str = "\"" + str + "\"";
            }
            else if (type == typeof(Int32))
            {
                str = "\"" + str + "\"";
            }
            else if (type == typeof(int))
            {
                str = "\"" + str + "\"";
            }

            return str;
        }
        /// <summary>
        /// 过滤特殊字符
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        private static string String2Json(String s)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                char c = s.ToCharArray()[i];
                switch (c)
                {
                    case '\"':
                        sb.Append("\\\""); break;
                    case '\\':
                        sb.Append("\\\\"); break;
                    case '/':
                        sb.Append("\\/"); break;
                    case '\b':
                        sb.Append("\\b"); break;
                    case '\f':
                        sb.Append("\\f"); break;
                    case '\n':
                        sb.Append("\\n"); break;
                    case '\r':
                        sb.Append("\\r"); break;
                    case '\t':
                        sb.Append("\\t"); break;
                    default:
                        sb.Append(c); break;
                }
            }
            return sb.ToString();
        }


        /// <summary>    
        /// Json转DataTable    
        /// </summary>    
        /// <param name="json"></param>   
        /// /// <returns></returns>    
        public static System.Data.DataTable Json2Dtb(string json)
        {        
            JavaScriptSerializer jss = new JavaScriptSerializer();        
            ArrayList dic = jss.Deserialize<ArrayList>(json);
            System.Data.DataTable dtb = new System.Data.DataTable();        
            if (dic.Count > 0)        {            
                foreach (Dictionary<string, object> drow in dic)            
                {               
                    if (dtb.Columns.Count == 0)                
                    {                    
                        foreach (string key in drow.Keys)                    
                        {                        
                            dtb.Columns.Add(key, drow[key].GetType());                    
                        }                
                    }
                    System.Data.DataRow row = dtb.NewRow();                
                    foreach (string key in drow.Keys)                
                    {                    
                        row[key] = drow[key];                
                    }                
                    dtb.Rows.Add(row);            
                }        
            }        
            return dtb;    
        }

        /// <summary>    
        /// DataTable转Json    
        /// </summary>    
        /// <param name="dtb"></param>    
        /// <returns></returns>    
        public static string Dtb2Json(System.Data.DataTable dtb)
        {        
            JavaScriptSerializer jss = new JavaScriptSerializer();        
            ArrayList dic = new ArrayList();
            foreach (System.Data.DataRow row in dtb.Rows)        
            {            
                Dictionary<string, object> drow = new Dictionary<string, object>();
                foreach (System.Data.DataColumn col in dtb.Columns)
                {                
                    drow.Add(col.ColumnName, row[col.ColumnName]);            
                }            dic.Add(drow);        
            }        return jss.Serialize(dic);    
        }

     

        /// <summary>
        /// 获取DataTable的栏位
        /// </summary>
        /// <param name="DT"></param>
        /// <returns></returns>
        public static HashSet<String> GetDTCols(System.Data.DataTable DT)
        {
            HashSet<String> HS = new HashSet<string>();
            foreach (System.Data.DataColumn col in DT.Columns)
            {
                HS.Add(col.ColumnName);
            }
            return HS;
        }
        /// <summary>
        /// 将JSON数据格转换实体对象。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strJson"></param>
        /// <returns></returns>
        public static T JSonToObject<T>(string strJson)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            T t = default(T);
            try
            {
                t = jss.Deserialize<T>(strJson);
            }
            catch
            {

            }
            if (t == null)
            {
                try
                {
                    t = Activator.CreateInstance<T>();
                    t = (T)JSONtoOject(t, strJson);
                }
                catch { }
            }
            if (t != null)
            {
                return t;
            }
            else
            {
                return default(T);
                //return Activator.CreateInstance<T>();
            }
        }
        /// <summary>
        /// 将对象值转化成字符串值
        /// </summary>
        /// <param name="obj">需要转化的对象</param>
        /// <returns>返回转化的字符</returns>
        public static string ObjectToString(object obj)
        {
            string Value = null;
            if (obj == null)
            {
                Value = "null";
            }
            if (obj is System.Boolean)
            {
                bool bl = ((Boolean)obj);
                Value = bl ? "True" : "False";
            }
            if (obj is System.Int32)
            {
                Value = ((Int32)obj).ToString();
            }
            if (obj is System.Int64) //2012-7-12日添加
            {
                Value = ((Int64)obj).ToString();
            }
            if(obj is System.Int16) //2012-6-21加
            {
                Value=((Int16)obj).ToString();
            }
            if (obj is System.Byte) //2012-7-7加
            {
                Value = ((Byte)obj).ToString();
            }
            if (obj is System.DateTime)
            {
                Value = ((DateTime)obj).ToString("yyyy-MM-dd HH:mm").Replace("00:00", "");
            }
            if (obj is System.String)
            {
                Value = ((String)obj).ToString();
            }
            if (obj is System.Decimal)
            {
                Value = ((Decimal)obj).ToString();
            }
            if (obj is System.Double)
            {
                Value = ((Double)obj).ToString();
            }
            if (obj is System.Guid)
            {
                Value = ((Guid)obj).ToString();
            }
            return Value;
        }


        /// <summary>
        /// 将JSON格式转化成对象实例
        /// </summary>
        /// <param name="JSON"></param>
        /// <returns></returns>
        public static object JSONtoObject(string strEntity, string json)
        {
            //T instance = Activator.CreateInstance<T>();
            object instance = getEntity(strEntity);
            Type t = instance.GetType();
            PropertyInfo[] Mypropertyinfos = t.GetProperties();
            Hashtable hashtable = JsonToHashTalbe(json);
            foreach (PropertyInfo pi in Mypropertyinfos)
            {
                try
                {
                    SetPropertyValue(instance, pi.Name, hashtable[pi.Name]);
                }
                catch (System.Exception)
                {
                    // throw e;
                }
            }
            return instance;
        }


        public static object JSONtoOject(object instance, string json)
        {
            //T instance = Activator.CreateInstance<T>();

            //object instance = getEntity(strEntity);
            Type t = instance.GetType();
            PropertyInfo[] Mypropertyinfos = t.GetProperties();
            Hashtable hashtable = JsonToHashTalbe(json);
            foreach (PropertyInfo pi in Mypropertyinfos)
            {
                try
                {
                    SetPropertyValue(instance, pi.Name, hashtable[pi.Name]);
                }
                catch (System.Exception)
                {
                    // throw e;
                }
            }

            return instance;
        }
        /// <summary>
        /// 仅用于简单的实体对象
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static Hashtable JsonToHashTalbe(string json)
        {
            if (json.Length < 5)
            {
                return new Hashtable();
            }
            string strJson = json;
            strJson = strJson.Remove(0, 2);
            strJson = strJson.Remove(strJson.Length - 2, 2);
            strJson = strJson.Replace("\", \"", "\",\""); // 该行是用于IE6,IE7的Json字符串处理
            string[] s = { "\",\"" };
            string[] s1 = { "\":\"" };
            string[] strArray = strJson.Split(s, StringSplitOptions.None);
            Hashtable hashtable = new Hashtable();
            foreach (string str in strArray)
            {
                string[] _strArray = str.Split(s1, StringSplitOptions.None);
                if (_strArray.Length > 1)
                {
                    if (_strArray[0].IndexOf('"') == 1)
                    {
                        hashtable.Add(_strArray[0].Remove(0, 1), UrlDecode(_strArray[1]));
                    }
                    else
                    {
                        hashtable.Add(_strArray[0], UrlDecode(_strArray[1]));
                    }
                }
            }
            return hashtable;

        }

        #region 动态获取和设置相关对象的属性的值
        /// <summary>
        /// 获取对象属性的值
        /// </summary>
        /// <param name="obj">Obj the type is object</param>
        /// <param name="name">name is Preperty name</param>
        /// <returns></returns>
        public static object GetPropertyValue(object obj, string name)
        {
            object obj1 = null;
            try
            {
                obj1 = obj.GetType().InvokeMember(name, BindingFlags.GetProperty, null, obj, null);
            }
            catch
            {
            }
            return obj1;
        }

        /// <summary>
        /// 如果某个object有名为PropertyName的属性，则获取此属性值
        /// 如果没有，则返回null
        /// </summary>
        private static string GetObjectProperty(object obj, string propertyName)
        {
            try
            {
                if (obj == null)
                    return null;
                else
                {
                    PropertyInfo p = obj.GetType().GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance);
                    if (p == null)
                        return null;
                    else
                        return Convert.ToString(p.GetValue(obj, null));
                }

            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// 设置实体对象的属性的值
        /// </summary>
        /// <param name="obj">实体对象</param>
        /// <param name="name">实体对象的属性</param>
        /// <param name="value">要设置的值</param>
        public static void SetPropertyValue(object obj, string name, object value)
        {
            try
            {
                object[] objArray1 = new object[1];
                Type type1 = obj.GetType().GetProperty(name).PropertyType;
                //if (type1.Name == "Nullable`1")
                //{
                //    value = ConvertInt(value.ToString());
                //}
                if (value.GetType() == typeof(string))
                {
                    value = value.ToString().Replace("[B]", "'");
                }
                objArray1[0] = ChangeTypes(value, type1);
                obj.GetType().InvokeMember(name, BindingFlags.SetProperty, null, obj, objArray1);
            }
            catch
            {
            }
        }

        public static Type GetPropertyType(object obj, string name)
        {
            if (obj is FL.DBModule.DataTableBaseEntity)
            {
                //(obj as FL.DBModule.DataTableBaseEntity)
            }
            return obj.GetType().GetProperty(name).PropertyType;
        }
        #endregion


        public static object ChangeTypes(object value, Type conversionType)
        {
            if (conversionType.IsGenericType &&
                conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                if (value == null)
                    return null;

                System.ComponentModel.NullableConverter nullableConverter
                    = new System.ComponentModel.NullableConverter(conversionType);

                conversionType = nullableConverter.UnderlyingType;
            }
            if (conversionType.ToString().IndexOf("Guid") > 0)
            {

                value = new Guid(value.ToString());
            }
            return Convert.ChangeType(value, conversionType);
        }

        /// <summary>
        /// 获取属性的值
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static T GetPropertyValue<T>(object obj, string name)
        {
            try
            {
                return (T)FL.Common.Globals.GetPropertyValue(obj, name);
            }
            catch (System.Exception e)
            {
                throw e;
            }
        }


        public static Type GetProgertyType(string name, object obj)
        {
            return FL.Common.Globals.GetPropertyType(obj, name);
        }

        public static IList<T> JSONtoOject<T>(string strEntity, string strjson)
        {
            IList<T> list = new List<T>();
            try
            { 
                object[] _list = ((object[])(new System.Web.Script.Serialization.JavaScriptSerializer()).DeserializeObject(strjson));// as Dictionary<string,object>
                foreach (object _o in _list)
                {
                    Dictionary<string, object> dic = _o as Dictionary<string, object>;
                    FL.DBModule.DataTableBaseEntity entity = new DBModule.DataTableBaseEntity();
                    entity.TableName = strEntity;
                    entity.CreateDT();
                    entity.FieldValue = (dic);
                    entity.SetValue(dic);
                    list.Add(FL.Common.Globals.JSonToObject<T>(FL.Common.Globals.DataRowToJSON(entity.DRow)));
                }
            }
            catch
            {
            }
            return list;
        }
    }


}
